package com.custom.BluetoothServer;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.widget.TextView;

//服务器端
public class MainActivity extends AppCompatActivity implements ServiceConnection {
    private Intent intent;
    private MyService.Bind bind = null;
    private Handler handler = new Handler();
    private TextView mshowtev;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mshowtev = findViewById(R.id.tev_show);
        intent = new Intent(MainActivity.this, MyService.class);
        startService(intent);
        bindService(intent, this, Context.BIND_AUTO_CREATE);
    }


    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        /*绑定服务*/
        bind = (MyService.Bind) service;/*相关联*/
        /*接口回调*/
        bind.getService().setCallback(new MyService.Callback() {
            @Override
            public void onDataChange(String data) {
                Message msg = new Message();
                Bundle b = new Bundle();
                b.putString("data", data);
                msg.setData(b);
                msg.what = 2;
                handler.sendMessage(msg);
            }
        });
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }


    public class Handler extends android.os.Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 2:
                    mshowtev.setText(msg.getData().getString("data"));
                    break;
            }

            super.handleMessage(msg);
        }
    }
}


